package com.ysucloud.manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.ysucloud.manager.DTO.OrderDTO;
import com.ysucloud.manager.Utils.TimeUtil;
import com.ysucloud.manager.VO.CountVO;
import com.ysucloud.manager.VO.ResultListVO;
import com.ysucloud.manager.VO.ResultObjectVO;
import com.ysucloud.manager.exception.NullParameterException;
import com.ysucloud.manager.repository.OrderMasterRepository;
import com.ysucloud.manager.server.OrderServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * Description: manager
 * Created by 刘翰文 on 2019/6/27 17:14
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderServer orderServer;

    @Autowired
    OrderMasterRepository orderMasterRepository;

    /** 获取订单列表 */
    @PostMapping("/list")
    public ResultListVO getAll(){

        List<OrderDTO> list = orderServer.getAll();

        ResultListVO result = new ResultListVO();
        result.setData(list);

        return result;
    }

    /** 获取单个订单详情 */
    @PostMapping("/detail")
    public ResultObjectVO getOne(@RequestBody JSONObject jsonObject){
        Integer orderId = jsonObject.getInteger("id");
        if(orderId == null){
            throw new NullParameterException();
        }
        ResultObjectVO result = new ResultObjectVO();

        OrderDTO orderDTO = orderServer.getOne(orderId);

        result.setData(orderDTO);

        return result;
    }

    /** 完成订单 */
    @PostMapping("/finish")
    public ResultListVO finishOrder(@RequestBody JSONObject jsonObject){
        Integer orderId = jsonObject.getInteger("id");
        if(orderId == null){
            throw new NullParameterException();
        }

        ResultListVO result = new ResultListVO();

        orderServer.finishOrder(orderId);

        return result;
    }

    /** 订单数量 */
    @PostMapping("/count")
    public ResultObjectVO count(){
        CountVO countVO = new CountVO();
        countVO.setAllCount(orderMasterRepository.countAllBy());
        countVO.setWeekCount(orderMasterRepository.countByDate(TimeUtil.addDate(- 7),new Date()));
        countVO.setMouthCount(orderMasterRepository.countByDate(TimeUtil.addDate(- 30),new Date()));

        ResultObjectVO result = new ResultObjectVO();
        result.setData(countVO);

        return result;
    }

    /** 一周内订单数量（每日） */
    @PostMapping("/week")
    public ResultObjectVO weekCount(){
        return new ResultObjectVO(orderServer.countWeek());
    }
}
